package com.dfhz.ken.zermall.UI.activity;

import android.app.Activity;
import android.content.CursorLoader;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dfhz.ken.zermall.R;
import com.dfhz.ken.zermall.utils.DownImageUtils;
import com.dfhz.ken.zermall.utils.MyViewHolder;
import com.dfhz.ken.zermall.utils.ToastUtil;
import com.dfhz.ken.zermall.utils.ToolBarUtils;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import widget.customview.CheckableLinearLayout;

/**
 * 多选图片相册
 *
 * @author sunwei
 */
public class LocalImageActivity extends AppCompatActivity {

    @Bind(R.id.toolbar)
    Toolbar mToolbar;

    @Bind(R.id.gridViewImageAcitivty)
    GridView mGridView;
    @Bind(R.id.txt_imageActivity_imageCount)
    TextView mImageCount;
    @Bind(R.id.btn_imageActivity_send)
    Button mBtnSend;

    private ArrayList<String> mUirs = new ArrayList<String>();
    private ArrayList<String> mUriSends = new ArrayList<String>();

    private ImageAdapter imageAdapter;

    public static final String SEND_IMAGE_URIS = "send_image_uris";

    private ImageLoader options;
    private int listsize;//当前图片长度
    private int maxsize;//最大图片长度

    private String place;//区分是定制界面 还是发布产品界面

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.activity_show_image);
        ButterKnife.bind(this);
        ToolBarUtils.show(LocalImageActivity.this, mToolbar, true, "选择图片");

        listsize = getIntent().getIntExtra("listsize", 0);//获取上个界面的图片列表长度（限制选择长度）

        place = getIntent().getStringExtra("place");
        if (place != null && place.equals("dingzhi")) {
            maxsize = 4;
        } else if (place != null && place.equals("evidence")) {
            maxsize = 3;
        } else {
            maxsize = 3;
        }


        options = ImageLoader.getInstance();

        imageAdapter = new ImageAdapter(mUirs);

        mGridView.setAdapter(imageAdapter);

        loadImages();

        mBtnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listsize == 0) {
                    // 第一次选择图片时，判断如果选中的图片大于9张，则不再添加
                    if (mUriSends.size() > maxsize) {
                        ToastUtil.show(LocalImageActivity.this, "一件产品最多只能有" + maxsize + "张图片");
                        return;
                    }
                } else {
                    if ((listsize + mUriSends.size()) > maxsize) {
                        ToastUtil.show(LocalImageActivity.this, "一件产品最多只能有" + maxsize + "张图片");
                        return;
                    }
                }
//                //将前面记住的图片数清零
//                SendContentActivity.picsize=0;

                Intent intent = new Intent();
                intent.putStringArrayListExtra(SEND_IMAGE_URIS, mUriSends);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });

    }

    private class ImageAdapter extends ArrayAdapter<String> {
        public ImageAdapter(List<String> strings) {
            super(LocalImageActivity.this, 0, strings);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(
                        R.layout.list_item_show_image, null);
            }

            ImageView mImv = MyViewHolder.get(convertView, R.id.imv_picture);
            CheckableLinearLayout checkableLinearLayout =
                    MyViewHolder.get(convertView, R.id.checkableLinearLayout);

            final String uri = getItem(position);

            options.init(DownImageUtils.configImage(LocalImageActivity.this));
            options.displayImage(uri, mImv, DownImageUtils.getOption());
            //ImageLoader.getInstance().displayImage(uri, mImv, options);

            checkableLinearLayout
                    .setOncheckedChangeListener(new CheckableLinearLayout.OncheckedChangeListener() {

                        @Override
                        public void onCheckedChange(boolean isChecked) {
                            if (isChecked) {
                                if (!mUriSends.contains(uri))
                                    mUriSends.add(uri);
                                if (mUriSends.size() > maxsize) {
                                    Toast.makeText(LocalImageActivity.this, "一件产品最多只能有" + maxsize + "张图片", Toast.LENGTH_SHORT).show();
                                }
                            } else {
                                mUriSends.remove(uri);
                            }
                            mImageCount.setText(mUriSends.size() + "");
                        }
                    });

            return convertView;
        }
    }

    private void loadImages() {
        Cursor cursor = null;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
            CursorLoader loader = new CursorLoader(LocalImageActivity.this,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{
                    MediaStore.Images.Media.DATA,
                    MediaStore.Images.Media._ID}, null, null,
                    MediaStore.Images.Media._ID);
            cursor = loader.loadInBackground();
        } else {
            cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    new String[]{
                            MediaStore.Images.Media.DATA,
                            MediaStore.Images.Media._ID}, null, null,
                    MediaStore.Images.Media._ID);
        }

        try {
            cursor.moveToFirst();

            while (!cursor.isBeforeFirst() && !cursor.isAfterLast()) {
                String item = new String();
                int dataColumnIndex = cursor
                        .getColumnIndex(MediaStore.Images.Media.DATA);
                item = cursor.getString(dataColumnIndex);
                if (item.endsWith("png") || item.endsWith("jpg")) {
                    mUirs.add("file://" + item);//
                }
                cursor.moveToNext();
            }
            Collections.reverse(mUirs);
            imageAdapter.notifyDataSetChanged();
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtil.show(LocalImageActivity.this, "加载图片出错，请检测是否插入内存卡");
            finish();
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

}
